package com.ruoyi.framework.config;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.manage.config.AppConfig;
import com.ruoyi.manage.domain.AppUser;
import com.ruoyi.manage.service.IAppUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: wwy
 * @Date: 2020/12/29 13:26
 */
@Component
public class AppApiInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IAppUserService appUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //进行token验证
        LoginUser loginUser = tokenService.getLoginUser(request);


        if(loginUser != null){
            //刷新token时间
            tokenService.verifyToken(loginUser);
        }else{
            throw new AccessDeniedException("app未进行认证");
        }
        //获取账号绑定状态
        int bindingStatus = getUserBindingStatus(loginUser.getOpenId());
        if(bindingStatus == 0){
            //账号未绑定
            throw new AccessDeniedException("app未进行认证");
        }
        return true;
    }

    /**
     * 获取用户状态
     * @param openId
     * @return
     */
    private int getUserBindingStatus(String openId){
        AppUser appUser = new AppUser();
        appUser.setOpenId(openId);
        List<AppUser> appUsers = appUserService.selectAppUserList(appUser);
        AppUser appUser1 = appUsers.get(0);
        return appUser1.getBindingStatus();
    }
}
